var myDate = new Date();
$(function(){
  var startDate=null;
  var endDate=null;
  $("#start").click(function(){
    if($("#end").val()!=""){
      endDate="'"+$("#end").val()+"'";
    }
    $('#start').datepicker('setEndDate', endDate);
  });
  //当$("#end")的值不为空时$("#start")的endDate为$("#end")的值
  $("#end").click(function(){
    if($("#start").val()!=""){
      startDate="'"+$("#start").val()+"'";
    }
    //console.log(startDate);
    $('#end').datepicker('setStartDate', startDate);
  });

  $("#start").datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd',
    orientation : 'top',
    todayHighlight:true
  });

  $("#end").datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd',
    orientation : 'top',
    todayHighlight:true
  });


  $('#start').val(myDate.getFullYear()+'-'+(myDate.getMonth()+1)+'-'+1);
  $('#end').val(myDate.getFullYear()+'-'+(myDate.getMonth()+1)+'-'+myDate.getDate());
});

//表格
$(function() {
  $.jgrid.defaults.styleUI = "Bootstrap";

  $("#table_list").jqGrid({


    datatype: "json",                                              //请求的数据类型
    mtype: "POST",                                                  //请求类型
    height: 330,                                                   //设置高度
    autowidth: true,                                               //自动匹配宽度
    shrinkToFit: true,
    rowNum: 10,                                                    //每页显示记录数
    rowList: [10, 20, 30],                                       //分页选项，可以下拉选择每页显示记录数
    colNames: ["id", "问卷标题","创建时间", "是否启用", "首页推送", "微信推送", "邮件推送","立即邮件推送"],                //数据列名称（数组）
    //数据列各参数信息设置
    colModel: [{name: "id", index: "id", width: 20},
      {name: "title", index: "title", width: 50},
      {name: "ctime", index: "ctime", width: 30,formatter:ctime,},
      {name: "start", index: "start", width: 30,formatter:creatbtn},
      {name: "pagestart", index: "pagestart", width: 30,formatter:creatbtn,},
      {name: "wechatstart", index: "wechatstart", width: 30,formatter:creatbtn,},
      {name: "mailstart", index: "mailstart", width: 30,formatter:creatbtn,},
      {name: "", index: "", width: 20,sortable:false,formatter:sendbtn},

    ],
    pager: "#pager_list",                                         //表格数据关联的分页条，html元素
    viewrecords: true,                                            //显示总记录数
    //这是一个数组，用于设置jqGrid将要向Server传递的参数名称
    jsonReader: {
      id: "id",                                           //相当于设置主键
      root: "dataList",                                        //Json数据
      records: "record",                                      //总记录数
      repeatitems: false
    },
    multiselectWidth: 25,                                          //设置多选列宽度
    multiselect: false,                                            //可多选，出现多选框
    gridview: true,                                                 //加速显示
    sortable: true,                                                //可以排序
    sortname: 'ctime',
    sortorder: "desc",                                //可以排序
    hidegrid: false,
   // toppager: true ,                                               //同步导航栏至表格顶部


  });





  /*********************************
   功能：隐藏底部的导行栏
   *********************************/
  $('#table_list_toppager_center').hide();   //隐藏底部的导行栏



  $(window).bind("resize", function () {
    var width = $(".jqGrid_wrapper").width();
    $("#table_list").setGridWidth(width);
  });



  $("#queryButton").click(function () {
    var title = $("#title").val();
    var start = $("#start").val();
    var end = $("#end").val();
    if(end==""||start==""){
      if(end=="")
      {
        end=start;
      }
      else if( start=="")
      {
        start=end;
      }
    }
    if(end!=""&&start!=""){
      start+=" 00:00:00";
      end+=" 23:59:59";
    }

    $("#table_list").jqGrid('setGridParam', {
      url: $(path).val() + '/Config/getQuestionnaireConfig',
      dataType: 'json',
      postData: {
        title: title,
        start: start,
        end: end,
      },
      page: 1
    }).trigger('reloadGrid'); //重新载入
  });
  function ctime(cellValue){
    var date =new Date(cellValue);
    var year=date.getYear()+1900;
    var month=date.getMonth()+1;
    var day=date.getDate();

    return year+"-"+month+"-"+day;
  }
  function start(cellValue){
  if(cellValue=="0") return "启用";
    else return "未启用";
  }

function creatbtn(cellValue,object){
  var id=object.rowId;
  var name=object.colModel.name;
  var btn="<button class='btn btn-red  btn-sm '  type='button' value='"+cellValue+"'  onclick='changeStart(this,\""+id+"\",\""+name+"\",this.value)'>状态(启用)-->关闭</button>";
  if(!cellValue)
    btn="<button class='btn btn-success btn-sm'   type='button' value='"+cellValue+"' onclick='changeStart(this,\""+id+"\",\""+name+"\",this.value)'>状态(关闭)-->启用</button>";
 return btn;


}
function sendbtn(cellValue,object){
  var id=object.rowId;
  var   btn="<button class='btn btn-success btn-sm'   type='button'  onclick='sendmail(\""+id+"\")'>推送</button>";
 return btn;


}



});


function sendmail(id){
  if (id) {
    var data = $("#table_list").jqGrid('getRowData', id);
    if((data.mailstart).indexOf("true")>0&&(data.start).indexOf("true")){

      $.get($("#path").val()+"/Email/sendQmail?id="+id,function(json){
      var data=JSON.parse(json);
        toastAlert(data.status,data.operate,data.msg,3000);
      });

    }
    else{
      toastAlert("error","操作失败","问卷或邮件推送未启用!",3000);
    }
  }
}

function changeStart(e,id,name,start){
  var flag;
  if(start=="true"){
    $(e).text("关闭中...").attr("disabled","true").removeClass("btn-red");
    flag=false;
  }
  else{
    $(e).text("启动中...").attr("disabled","true").removeClass("btn-success");
    flag=true;
  }
  $.get($(path).val() + "/Config/updateQuestionnaireConfig?"+name+"="+flag+"&id="+id+"&title="+name,
      function(json){
          var result=JSON.parse(json);
        $(e).text(result.msg)
        if(result.status=="success"){
        if(start=="true"){
          $(e).text("状态(关闭)-->启用").removeAttr("disabled").addClass("btn-success").val(flag);
        }
        else{
          $(e).text("状态(启用)-->关闭").removeAttr("disabled").addClass("btn-red").val(flag);
        }

        }
        else{
          if(start!="true"){
            $(e).text("状态(关闭)-->启用").removeAttr("disabled").addClass("btn-success");
          }
          else{
            $(e).text("状态(启用)-->关闭").removeAttr("disabled").addClass("btn-red");
          }
        }
      }
  );
}